package view;

import controller.UserController;
import model.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 用户注册对话框
 */
public class RegisterDialog extends JDialog {
    private JTextField studentIdField;
    private JTextField nameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JTextField phoneField;
    private JTextField emailField;
    private JButton registerButton;
    private JButton cancelButton;

    private UserController userController;
    private Runnable onCloseCallback;

    public RegisterDialog(Runnable onCloseCallback) {
        super((JFrame) null, "用户注册", true);
        this.onCloseCallback = onCloseCallback;
        userController = new UserController();
        initComponents();
        setupLayout();
        setupEventListeners();
    }

    private void initComponents() {
        setSize(480, 650);
        setLocationRelativeTo(getParent());
        setResizable(false);

        // 设置对话框背景色
        getContentPane().setBackground(new Color(250, 251, 252));

        studentIdField = new JTextField(15);
        nameField = new JTextField(15);
        passwordField = new JPasswordField(15);
        confirmPasswordField = new JPasswordField(15);
        phoneField = new JTextField(15);
        emailField = new JTextField(15);

        // 美化输入框
        styleTextField(studentIdField);
        styleTextField(nameField);
        styleTextField(passwordField);
        styleTextField(confirmPasswordField);
        styleTextField(phoneField);
        styleTextField(emailField);

        registerButton = new JButton("注册");
        cancelButton = new JButton("取消");

        // 美化按钮
        styleButton(registerButton, new Color(34, 197, 94), Color.WHITE); // 绿色注册按钮
        styleButton(cancelButton, new Color(229, 231, 235), new Color(75, 85, 99)); // 灰色取消按钮
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 添加标题面板 - 减少边距
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(new Color(255, 255, 255));
        titlePanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(229, 230, 235)),
                BorderFactory.createEmptyBorder(15, 0, 10, 0))); // 添加紧凑的内边距
        titlePanel.setPreferredSize(new Dimension(400, 50)); // 从60px减少到50px

        JLabel titleLabel = new JLabel("用户注册");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        titleLabel.setForeground(new Color(31, 41, 55));
        titlePanel.add(titleLabel);

        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBackground(new Color(255, 255, 255));
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 40, 25, 40)); // 减少上边距从30到20，下边距从30到25
        GridBagConstraints gbc = new GridBagConstraints();

        String[] labels = { "学号", "姓名", "密码", "确认密码", "手机", "邮箱" };
        JComponent[] fields = { studentIdField, nameField, passwordField,
                confirmPasswordField, phoneField, emailField };

        for (int i = 0; i < labels.length; i++) {
            // 标签 - 左列
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.insets = new Insets(i == 0 ? 10 : 15, 10, 5, 10);
            gbc.gridwidth = 1;
            JLabel label = new JLabel(labels[i] + "：");
            label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
            label.setForeground(new Color(55, 65, 81));
            label.setPreferredSize(new Dimension(80, 35));
            formPanel.add(label, gbc);

            // 输入框 - 右列
            gbc.gridx = 1;
            gbc.gridy = i;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.insets = new Insets(i == 0 ? 10 : 15, 5, 5, 10);
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            formPanel.add(fields[i], gbc);
        }

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setBackground(new Color(255, 255, 255));
        buttonPanel.add(registerButton);
        buttonPanel.add(cancelButton);

        gbc.gridx = 0;
        gbc.gridy = labels.length;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(20, 10, 10, 10);
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        formPanel.add(buttonPanel, gbc);

        // 底部版权信息面板
        JPanel bottomPanel = new JPanel();
        bottomPanel.setBackground(new Color(250, 251, 252));
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 15, 0));

        JLabel copyrightLabel = new JLabel("制作人：潘梦连   覃彩蜜", JLabel.CENTER);
        copyrightLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        copyrightLabel.setForeground(new Color(156, 163, 175));
        bottomPanel.add(copyrightLabel);

        add(titlePanel, BorderLayout.NORTH);
        add(formPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private void setupEventListeners() {
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleRegister();
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                if (onCloseCallback != null) {
                    onCloseCallback.run();
                }
            }
        });
    }

    private void handleRegister() {
        // 验证输入
        String studentId = studentIdField.getText().trim();
        String name = nameField.getText().trim();
        String password = new String(passwordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        String phone = phoneField.getText().trim();
        String email = emailField.getText().trim();

        if (studentId.isEmpty() || name.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写必填信息!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (!password.equals(confirmPassword)) {
            JOptionPane.showMessageDialog(this, "两次密码输入不一致!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try {
            User newUser = new User(studentId, name, password, phone, email, 0); // 默认为学生
            boolean success = userController.register(newUser);

            if (success) {
                JOptionPane.showMessageDialog(this, "注册成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
                if (onCloseCallback != null) {
                    onCloseCallback.run();
                }
            } else {
                JOptionPane.showMessageDialog(this, "注册失败，学号可能已存在!", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "注册失败: " + ex.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 美化按钮样式
     */
    private void styleButton(JButton button, Color backgroundColor, Color textColor) {
        button.setPreferredSize(new Dimension(90, 35));
        button.setBackground(backgroundColor);
        button.setForeground(textColor);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        button.setBorder(BorderFactory.createEmptyBorder(8, 16, 8, 16));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加圆角效果
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(backgroundColor.darker(), 1),
                BorderFactory.createEmptyBorder(6, 14, 6, 14)));

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor.darker());
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor);
            }
        });
    }

    /**
     * 美化输入框样式 - 确保合适的尺寸
     */
    private void styleTextField(JTextField textField) {
        textField.setPreferredSize(new Dimension(300, 40));
        textField.setMinimumSize(new Dimension(300, 40));
        textField.setMaximumSize(new Dimension(300, 40));

        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(217, 217, 217), 1),
                BorderFactory.createEmptyBorder(10, 12, 10, 12)));
        textField.setBackground(new Color(255, 255, 255));

        // 聚焦时的边框效果
        textField.addFocusListener(new java.awt.event.FocusListener() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(34, 197, 94), 2),
                        BorderFactory.createEmptyBorder(9, 11, 9, 11)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(217, 217, 217), 1),
                        BorderFactory.createEmptyBorder(10, 12, 10, 12)));
            }
        });
    }
}
